/**
 *
 */
package anyware.common.restlet.json;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.Validate;
import org.restlet.data.MediaType;
import org.restlet.resource.OutputRepresentation;

/**
 * @author keke<keke@codehaus.org>
 * @version $Revision: 107 $
 */
public class JSONRepresentation extends OutputRepresentation {
	private Object	   bean;
	private JSON	   json;
	private JsonConfig	jsonConfig;

	public JSONRepresentation(final JSON json, final MediaType mediaType) {
		super(mediaType);
		Validate.notNull(json);
		this.json = json;
	}

	public JSONRepresentation(final Object bean, final JsonConfig jsonConfig,
	        final MediaType mediaType) {
		super(mediaType);
		Validate.notNull(bean);
		Validate.notNull(jsonConfig);
		this.bean = bean;
		this.jsonConfig = jsonConfig;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.restlet.resource.Representation#write(java.io.OutputStream)
	 */
	@Override
	public void write(final OutputStream outputStream) throws IOException {
		if (json == null) {
			json = JSONSerializer.toJSON(bean, jsonConfig);
		}
		final Writer writer = new OutputStreamWriter(outputStream);
		json.write(writer);
		writer.flush();
	}
}
